<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="企业名称" prop="companyName">
        <el-input v-model="formData.companyName" placeholder="请输入企业名称" />
      </el-form-item>
      <el-form-item label="企业logo" prop="logoUrl">
        <UploadImg v-model="formData.logoUrl" />
      </el-form-item>
      <el-form-item label="所属行业" prop="industry">
        <el-input v-model="formData.industry" placeholder="请输入所属行业" />
      </el-form-item>
      <el-form-item label="企业性质" prop="companyNature">
        <el-input v-model="formData.companyNature" placeholder="请输入企业性质" />
      </el-form-item>
      <el-form-item label="企业规模" prop="companyScale">
        <el-input v-model="formData.companyScale" placeholder="请输入企业规模" />
      </el-form-item>
      <el-form-item label="企业福利" prop="companyWelfare">
        <el-input v-model="formData.companyWelfare" placeholder="请输入企业福利" />
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input v-model="formData.contacts" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="企业邮箱" prop="mail">
        <el-input v-model="formData.mail" placeholder="请输入企业邮箱" />
      </el-form-item>
      <el-form-item label="省市区">
        <el-cascader
          v-model="selectedOptions"
          :options="regionData"
          @change="handleChange"
          placeholder="请选择省市区"
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入详细地址" />
      </el-form-item>
      <el-form-item label="企业简介" prop="companyProfile">
        <Editor v-model="formData.companyProfile" height="150px" />
      </el-form-item>
      <el-form-item label="优质雇主" prop="superEmployer">
        <el-radio-group v-model="formData.superEmployer">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="招聘截止" prop="hireTime">
        <el-date-picker
          v-model="formData.hireTime"
          type="date"
          value-format="x"
          placeholder="选择招聘截止"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { CompanyApi, CompanyVO } from '@/api/member/company'
import {
  regionData, codeToText
} from 'element-china-area-data'
/** 企业 表单 */
defineOptions({ name: 'CompanyForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
let selectedOptions = ref([])
const selectedAddress = ref('')
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  companyName: undefined,
  logoUrl: undefined,
  industry: undefined,
  companyNature: undefined,
  companyScale: undefined,
  companyWelfare: undefined,
  contacts: undefined,
  phone: undefined,
  mail: undefined,
  provinceId: undefined,
  provinceName: undefined,
  cityId: undefined,
  cityName: undefined,
  districtId: undefined,
  districtName: undefined,
  address: undefined,
  companyProfile: undefined,
  superEmployer: undefined,
  hireTime: undefined
})
const formRules = reactive({
  companyName: [{ required: true, message: '企业名称不能为空', trigger: 'blur' }],
  logoUrl: [{ required: true, message: '企业logo不能为空', trigger: 'blur' }],
  industry: [{ required: true, message: '所属行业不能为空', trigger: 'blur' }],
  contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
  mail: [{ required: true, message: '企业邮箱不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  hireTime: [{ required: true, message: '招聘截止不能为空', trigger: 'blur' }]
})
const handleChange = (value) => {
  formData.value.provinceId = value[0]
  formData.value.cityId = value[1]
  formData.value.districtId = value[2]
  const [province, city, district] = value.map(code => codeToText[code])
  formData.value.provinceName = province
    formData.value.cityName = city
      formData.value.districtName = district
  formData.value.address = `${province} ${city} ${district}`
}
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CompanyApi.getCompany(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CompanyVO
    if (formType.value === 'create') {
      await CompanyApi.createCompany(data)
      message.success(t('common.createSuccess'))
    } else {
      await CompanyApi.updateCompany(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  selectedOptions = []
  formData.value = {
    id: undefined,
    companyName: undefined,
    logoUrl: undefined,
    industry: undefined,
    companyNature: undefined,
    companyScale: undefined,
    companyWelfare: undefined,
    contacts: undefined,
    phone: undefined,
    mail: undefined,
    provinceId: undefined,
    provinceName: undefined,
    cityId: undefined,
    cityName: undefined,
    districtId: undefined,
    districtName: undefined,
    address: undefined,
    companyProfile: undefined,
    superEmployer: undefined,
    hireTime: undefined
  }
  formRef.value?.resetFields()
}

</script>
